import {
	defineStore
} from 'pinia'


//表格树
const tableTree = (data) => {
	let tree = [];
	let arr = JSON.parse(JSON.stringify(data));
	let fn = (arr, pid = 0, level = 0) => {
		let childCount = arr.filter(item => item.pid === pid).length;
		let childNum = 0; // 初始化为 1
		arr.forEach(item => {
			if (item.pid === pid) {
				childNum++; // 更新子节点计数
				if (item.pid != 0) {
					let nbspStr = '│'.repeat(level - 1); // 上一级有子节点时，当前节点前有竖线
					let symbolStr = childNum < childCount ? '├' : '└'; // 最后一个子节点使用 '└'
					item.name = `${nbspStr}${symbolStr}${item.name}`;
				}
				tree.push(item);

				fn(arr, item.id, level + 1);

			}
		});
	};
	fn(arr);
	return tree;
}


//下拉树
const dataPickerTree = (data) => {

	let arr = JSON.parse(JSON.stringify(data));
	const fn = (arr, pid = 0) => {

		return arr
			.filter(item => item.pid === pid)
			.map(item => ({
				value: item.id,
				text: item.name,
				children: fn(arr, item.id)
			}));
	}
	return fn(arr)

}

//名称串（通过id 递归查询拼接分类名称）
const nameStrand = (data, id) => {
	let arr = JSON.parse(JSON.stringify(data));
	let str = "";
	let fn = (arr, id) => {
		arr.forEach(item => {
			if (item.id === id) {
				// console.log(item.name)
				str  =  item.name + '/' + str;
				if(item.pid !== 0){
					fn(arr, item.pid);
				}
				
			}
		});
	};
	fn(arr, id);
	return str.substring(0, str.length - 1)
}


const state = () => ({
	index: 1, //自增ID
	list: [{
			id: 1,
			name: '光模块',
			pid: 0
		},
		{
			id: 2,
			name: '电源模块',
			pid: 0
		},
		{
			id: 5,
			name: '交换机',
			pid: 2
		},

		{
			id: 6,
			name: '中兴',
			pid: 5
		},
		{
			id: 7,
			name: '路由器',
			pid: 2
		},
		{
			id: 8,
			name: '华为',
			pid: 5
		},

	]
})

const getters = {

}

const actions = {
	getNameStrand(id) { 
		return nameStrand(this.list,id)
	},
	getTableTree() {
		return tableTree(this.list)
	},
	getDataPickerTree() {
		return dataPickerTree(this.list)
	},
	save(data) { 
		if(!data.id){
			//新增
			data.id = this.index;
			this.index++;
			this.list.push(data);
		}else{
			//修改
			this.list = this.list.map(item => {
				if (item.id == data.id) {
					return data;
				}
				return item;
			})
		}
		
	},
	del(id) {
		this.list = this.list.filter(item => item.id != id);
	},

}

export const categoryStore = defineStore({
	id: 'category-store',
	state,
	getters,
	actions,
	persist: { //  持久化插件
		enabled: true, // 使用存储 
	}

})